package com.sample.view.components
{
	import com.sample.view.pages.TimeReports;
	import com.trg.flex.FlexUtils;
	import com.trg.flex.remote.RemoteCall;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.containers.HBox;
	import mx.controls.Label;

	[Event(name="fadeInComplete", type="flash.events.Event")]
	[Event(name="fadeOutComplete", type="flash.events.Event")]
	public class RemoteCallStatusBarItem extends HBox
	{
		public var call:RemoteCall;
		
		private var descLabel:Label;
		
		private var fadeOutPending:uint;
		
		public function RemoteCallStatusBarItem(call:RemoteCall)
		{
			super();
			this.call = call;
			
			descLabel = new Label();
			descLabel.text = call.description;
			addChild(descLabel);
			
			alpha = 0;
			fadeTimer = new Timer(100);
			fadeTimer.addEventListener(TimerEvent.TIMER, fadeTimerExec);
			
			if (call.longDescription) {
				toolTip = FlexUtils.replaceProperties(call.longDescription, call);
			}
		}
		
		private var fadeIncrement:Number = 0;
		private var fadeTimer:Timer;
		
		public function fadeIn(time:uint):void {
			fadeTimer.stop();
			if (time == 0 || alpha == 1) {
				alpha = 1;
				dispatchEvent(new Event("fadeInComplete"));
			} else {
				fadeIncrement = (1 - alpha) / (time / 100);
				fadeTimer.start();
			}
		}
		
		public function fadeOut(time:uint):void {
			if (fadeIncrement > 0) {
				fadeOutPending = time;
				addEventListener("fadeInComplete", function(event:Event) {
					fadeOut(fadeOutPending);
				});
				return; 
			}
			if (time == 0 || alpha == 0) {
				alpha = 0;
				dispatchEvent(new Event("fadeOutComplete"));
			} else {
				fadeIncrement = -alpha / (time / 100);
				fadeTimer.start();
			}
		}
		
		private function fadeTimerExec(event:TimerEvent):void {
			var a:Number = alpha + fadeIncrement;
			if (a <= 0) {
				alpha = 0;
				fadeTimer.stop();
				fadeIncrement = 0;
				dispatchEvent(new Event("fadeOutComplete"));
			} else if (a >= 1) {
				alpha = 1;
				fadeTimer.stop();
				fadeIncrement = 0;
				dispatchEvent(new Event("fadeInComplete"));
			} else {
				alpha = a;
			}
		}
		
	}
}